package com.example.weather.service;

import com.example.weather.dto.WeatherResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class SearchService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WeatherDataClient weatherDataClient;

    public WeatherResponse searchWeather(String cityid){


        WeatherResponse w = null;

        //1.先从缓存查
        w=(WeatherResponse) redisTemplate.opsForHash().get("weatherdata",cityid);
        if(w!=null){
            System.out.println("w:"+w.getResult().toString());
        }


        //2.缓存中没有再去第三方接口查
        if(w==null){
            synchronized (this){
                //再从缓存中查询一次，避免第二个、第三个...用户访问第三方接口
                w=(WeatherResponse) redisTemplate.opsForHash().get("weatherdata",cityid);
                if (w==null){
                    System.out.println("cityid: "+cityid);
                    w = weatherDataClient.search(cityid);
                    System.out.println("w: "+w.getResult());
                    //3.查了之后放入缓存再利用
                    redisTemplate.opsForHash().put("weatherdata",cityid,w);
                    System.out.println("----------------------放入缓存了------------------------");
                }
            }
        }
        return w;
    }

}
